import { history, Reducer, Effect } from 'umi';
import { fakeAccountLogin ,logout} from '@/services/login';
import { _LocaleContainer } from '@/.umi/plugin-locale/locale';
import { message } from 'antd';


export interface StateType {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      //发送请求执行登录
      const response = yield call(fakeAccountLogin, payload);
      // console.log(response);
      //判断是否登录成功
      if(response.status===undefined){
        message.success('登录成功')
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        });
        history.replace('/');
      }
     
    },

    *logout(_,{call}) {
      const load=message.loading('退出中。。。')

      //请求api，退出登录
      
      const response=yield call(logout)
      if(response.status===undefined){
        //删除本地存储的token和userInfo
        
        localStorage.removeItem('access_token')
        localStorage.removeItem('userInfo')
        message.success('退出成功')
        
        //重定向
        history.replace('/login')
      }
      load()
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      // setAuthority(payload.currentAuthority);
      //将token存入localStorage
      localStorage.setItem('access_token',payload.access_token)
      return {
        ...state,
      };
    },
  },
};

export default Model;
